/*
 * SessionManager.cpp
 * 
 * 会话管理器实现
 */

#include "network/SessionManager.h"
#include <muduo/base/Logging.h>

using namespace muduo;
using namespace muduo::net;

namespace framework {

SessionPtr SessionManager::addSession(const TcpConnectionPtr& conn) {
    auto session = std::make_shared<Session>(conn);
    
    std::lock_guard<std::mutex> lock(mutex_);
    sessions_[session->sessionId()] = session;
    connToSession_[conn->name()] = session->sessionId();
    
    LOG_INFO << "Session added: " << session->sessionId() 
             << ", total: " << sessions_.size();
    
    return session;
}

void SessionManager::removeSession(uint64_t sessionId) {
    std::lock_guard<std::mutex> lock(mutex_);
    
    auto it = sessions_.find(sessionId);
    if (it != sessions_.end()) {
        auto conn = it->second->getConnection();
        if (conn) {
            connToSession_.erase(conn->name());
        }
        sessions_.erase(it);
        
        LOG_INFO << "Session removed: " << sessionId 
                 << ", remaining: " << sessions_.size();
    }
}

SessionPtr SessionManager::getSession(uint64_t sessionId) {
    std::lock_guard<std::mutex> lock(mutex_);
    
    auto it = sessions_.find(sessionId);
    if (it != sessions_.end()) {
        return it->second;
    }
    return nullptr;
}

SessionPtr SessionManager::getSessionByConn(const TcpConnectionPtr& conn) {
    if (!conn) {
        return nullptr;
    }
    
    std::lock_guard<std::mutex> lock(mutex_);
    
    auto it = connToSession_.find(conn->name());
    if (it != connToSession_.end()) {
        auto sessionIt = sessions_.find(it->second);
        if (sessionIt != sessions_.end()) {
            return sessionIt->second;
        }
    }
    return nullptr;
}

size_t SessionManager::size() const {
    std::lock_guard<std::mutex> lock(mutex_);
    return sessions_.size();
}

void SessionManager::clear() {
    std::lock_guard<std::mutex> lock(mutex_);
    sessions_.clear();
    connToSession_.clear();
    LOG_INFO << "All sessions cleared";
}

void SessionManager::foreach(const std::function<void(const SessionPtr&)>& func) {
    std::lock_guard<std::mutex> lock(mutex_);
    for (const auto& pair : sessions_) {
        func(pair.second);
    }
}

} // namespace framework

